﻿using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using MQTTnet.AspNetCore;
using MQTTnet.Server;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MyMqtt
{
    public static class HostBuilderExtend
    {
        public static void RegistByConfig(this WebApplicationBuilder builder, int mqttport, int websocketPort)
        {
            builder.WebHost.UseKestrel(o =>
            {
                // This will allow MQTT connections based on TCP port 1883.
                o.ListenAnyIP(mqttport, l => l.UseMqtt());
                //o.ListenAnyIP(5080, l => l.UseMqtt());
                // This will allow MQTT connections based on HTTP WebSockets with URI "localhost:5000/mqtt"
                // See code below for URI configuration.
                o.ListenAnyIP(websocketPort); // Default HTTP pipeline
            });

            builder.Services.AddHostedMqttServer(
             optionsBuilder =>
             {

                // optionsBuilder.WithDefaultEndpointPort(5506);
             });

            builder.Services.AddMqttConnectionHandler();
            builder.Services.AddConnections();

         //builder.Services.AddSingleton<MqttController>();
        }
        public static void UserMqttSeve(this WebApplication app)
        {
            //var mqttcontorl = app.Services.GetService<MqttController>();

            app.UseEndpoints(
                endpoints =>
                {
                    endpoints.MapConnectionHandler<MqttConnectionHandler>(
                        "/mqtt",
                        httpConnectionDispatcherOptions => httpConnectionDispatcherOptions.WebSockets.SubProtocolSelector =
                            protocolList => protocolList.FirstOrDefault() ?? string.Empty);
                });
            app.UseMqttServer(
                    server =>
                    {
                        server.ValidatingConnectionAsync += MqttSeverHelper.ValidateConnection;
                        server.ClientConnectedAsync += MqttSeverHelper.OnClientConnected;
                        //客户端订阅
                        server.ClientSubscribedTopicAsync += MqttSeverHelper.ClientSubscribedTopicAsync;
                        //客户端取消订阅
                        server.ClientUnsubscribedTopicAsync += MqttSeverHelper.ClientUnsubscribedTopicAsync;
                        //
                        server.InterceptingPublishAsync += MqttSeverHelper.InterceptingPublishAsync;
                        
                       // MqttSeverHelper.PublishEvent += server.InjectApplicationMessage;



                    });
        }
      


    }
}
